package com.tek.ding.faceding.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.view.KeyEvent;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.jakewharton.rxbinding4.view.RxView;
import com.tek.ding.faceding.R;
import com.tek.ding.faceding.base.BaseActivity;
import com.tek.ding.faceding.base.FaceApplication;
import com.tek.ding.faceding.bean.AppVersion;
import com.tek.ding.faceding.bean.BaseBean;
import com.tek.ding.faceding.presenter.main.MainContract;
import com.tek.ding.faceding.presenter.main.MainModel;
import com.tek.ding.faceding.presenter.main.MainPresenter;
import com.tek.ding.faceding.ui.camera.CameraOpenGLActivity;
import com.tek.ding.faceding.ui.face.InputFaceActivity;
import com.tek.ding.faceding.ui.login.LoginActivity;
import com.tek.ding.faceding.utils.ActivityUtil;
import com.tek.ding.faceding.utils.BitmapUtil;
import com.tek.ding.faceding.utils.CheckNetwork;
import com.tek.ding.faceding.utils.Constants;
import com.tek.ding.faceding.utils.MyToastUtils;
import com.tek.ding.faceding.utils.SPUtils;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

@SuppressLint({"CheckResult", "Registered"})
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.MainView {

    private final static String TAG = MainActivity.class.getName();

    private TextView btnInputFace, btnSignIn, btnSignOut, btnReadBook;

    private String deviceId;
    private Integer versionCode;
    private String storeUid;
    private String activityName = MainActivity.class.getName();
    private AppVersion appVersion;

    // 腾讯定位
    private TencentLocationManager mLocationManager;
    private InnerLocationListener mLocationListener;

    public static void startActivity(Context context, String name) {
        context.startActivity(new Intent(context, MainActivity.class)
                .putExtra(INTENT_DATA, name));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected String setTitleName() {
        String storeName = getIntent().getStringExtra(INTENT_DATA);
        if (StringUtils.isNotBlank(storeName))
            return storeName;
        else
            return "叮叮书房";
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(new MainModel(), this);
    }

    @Override
    protected void init() {
        setTitleBackGone();

        btnInputFace = find(R.id.btn_input_face);
        btnSignIn = find(R.id.btn_sign_in);
        btnSignOut = find(R.id.btn_sign_out);
        btnReadBook = find(R.id.btn_read_book);

        // 获取设备标识
        deviceId = SPUtils.getString(Constants.DEVICE_ID, "");
        // 获取版本号
        versionCode = SPUtils.getInt(Constants.VERSION_CODE, 0);
        storeUid = SPUtils.getString(Constants.STORE_UID, "");

        RxView.clicks(tbTitle)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    MyToastUtils.show("设备号：" + deviceId + "\n版本号：" + versionCode);
                });

        RxView.clicks(btnInputFace)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (!CheckNetwork.isNetworkConnected(this))
                        MyToastUtils.showLong(getResources().getText(R.string.error_network));
                    else
                        InputFaceActivity.startActivity(this);
                });

        RxView.clicks(btnSignIn)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (!CheckNetwork.isNetworkConnected(this))
                        MyToastUtils.showLong(getResources().getText(R.string.error_network));
                    else
                        CameraOpenGLActivity.startActivity(this, 2);
                });

        RxView.clicks(btnSignOut)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (!CheckNetwork.isNetworkConnected(this))
                        MyToastUtils.showLong(getResources().getText(R.string.error_network));
                    else
                        CameraOpenGLActivity.startActivity(this, 3);
                });

        RxView.clicks(btnReadBook)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    if (!CheckNetwork.isNetworkConnected(this))
                        MyToastUtils.showLong(getResources().getText(R.string.error_network));
                    else
                        // 先扫脸查找会员，再去扫书的条形码
                        CameraOpenGLActivity.startActivity(this, 4);
                });

        // 开启定位
        startLocation();

        // 删除录入的人脸照片
        deletePhoto();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        moveTaskToBack(false);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

//        Log.e("MainActivity===", "onRestart");
        // 如果app在前台，则开启定位
        if (null != appVersion) {
//            Log.e("MainActivity===", "app在前台，发现更新信息");
            LoginActivity.startActivity(this, appVersion);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Log.e("MainActivity===", "onDestroy");

        // 退出页面前停止定位
        stopLocation();
    }

    @Override
    public void onCheckNewVersionOk(BaseBean<AppVersion> baseBean) {
        if (baseBean.success()) {
            if (baseBean.getData() != null) {
                // 发现有新版本
                appVersion = baseBean.getData();
//                Log.e("MainActivity===", "请求发现更新");
                // app在前台且在主页，回到登录页更新
                if (ActivityUtil.isAppForeground(MainActivity.this)) {
                    Activity currentActivity = FaceApplication.getInstance().getCurrentActivity();
                    String currentActivityName = currentActivity.getClass().getName();
                    if (currentActivityName.equals(activityName)) {
                        // 在前台主页，强制更新回到登录页
                        LoginActivity.startActivity(this, appVersion);
                        finish();
                    } else {
//                        Log.e("MainActivity===", "请求发现更新,不在主页");
                    }
                } else {
//                    Log.e("MainActivity===", "请求发现更新,app不在前台");
                }
//                Log.e("MainActivity===", "请求发现更新,关闭定位");
                // 关闭定位
                stopLocation();
            }
        }
    }

    /**
     * 定位初始化
     */
    private void startLocation() {
        /**
         * 设置用户是否同意隐私协议政策
         * 调用其他接口前必须首先调用此接口进行用户是否同意隐私政策的设置，传入true后才能正常使用定位功能
         */
        if (null == mLocationManager) {
            TencentLocationManager.setUserAgreePrivacy(true);

            Context applicationContext = getApplicationContext();
            mLocationManager = TencentLocationManager.getInstance(applicationContext);
            mLocationManager.setDeviceID(applicationContext, deviceId);
            mLocationListener = new InnerLocationListener(new WeakReference<>(this));

            int locMode = TencentLocationRequest.HIGH_ACCURACY_MODE;
            // 1小时定位一次
            long intervalTime = 60 * 60 * 1000;
            TencentLocationRequest request = TencentLocationRequest.create()
                    //用户可以自定义定位间隔，时间单位为毫秒，不得小于1000毫秒:
                    .setInterval(intervalTime)
                    //设置请求级别
                    .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA)
                    //是否允许使用GPS
                    .setAllowGPS(true)
                    //是否需要开启室内定位
                    .setIndoorLocationMode(true)
                    // 设置定位模式
                    .setLocMode(locMode)
                    // 设置GPS优先
                    .setGpsFirst(true)
                    // 用户可定义GPS超时时间，超过该时间仍然没有卫星定位结果将返回网络定位结果
                    .setGpsFirstTimeOut(10 * 1000);

            // 发起连续定位请求
            mLocationManager.requestLocationUpdates(request, mLocationListener);
        }
    }

    /**
     * 退出页面前停止定位
     */
    public void stopLocation() {
        if (null != mLocationManager) {
            mLocationManager.removeUpdates(mLocationListener);
            mLocationManager.disableForegroundLocation(true);
            mLocationManager = null;
            mLocationListener = null;
        }
    }

    /**
     * 删除录入的人脸照片
     */
    private void deletePhoto() {
        String folderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + BitmapUtil.PIC_DIR_NAME;
        File folderFile = new File(folderPath);

        File[] files = folderFile.listFiles();
        if (null != files && files.length > 0) {
            for (File file : files) {
                String fileName = file.getName();
                File targetFile = new File(folderPath, fileName);
                targetFile.delete();
            }
        }
    }

    /**
     * 定位结果监听
     */
    private class InnerLocationListener implements TencentLocationListener {

        private WeakReference<MainActivity> mMainActivityWRF;

        public InnerLocationListener(WeakReference<MainActivity> mainActivityWRF) {
            mMainActivityWRF = mainActivityWRF;
        }

        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int status, String reason) {
            if (null != mMainActivityWRF) {
                if (status == TencentLocation.ERROR_OK) {
                    // 定位成功
                    if (null != tencentLocation) {
                        String address = tencentLocation.getAddress();
                        if (StringUtils.isNotBlank(address) && CheckNetwork.isNetworkConnected(MainActivity.this)) {
                            double longitude = tencentLocation.getLongitude();
                            double latitude = tencentLocation.getLatitude();
                            // 检查更新
                            presenter.checkVersionV2(storeUid, address, longitude + "", latitude + "");
                        }
                    }
                }
            }
        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    }

}
